<script setup>
import {ref, onMounted} from 'vue'
import Msg from '@/components/message'
import { treeDictsApi, pageFilesApi, upFileApi } from '@/commons/api'
import TreeSel from '@/components/cascader/TreeSel.vue'
import axios from 'axios'
import Pager from '@/components/pager/Pager.vue'
import nopic from '@/assets/img/7.svg'
import { CScrollbar } from 'c-scrollbar'

// 定义父组件传来的参数
const props = defineProps({
  // 上传种类，1单图，2多图，3单文件，4多文件
  kind: {
    type: Number,
    required: true,
    default: 1
  },
  // 多个上传表单的区分
  types: {
    type: Number,
    default: 1
  },
  file: {
    type: Object,
    required: false,
    default: {id: '', name: '', url: ''}
  },
  files: {
    type: Array,
    required: false,
    default: []
  }
})

const fileRef = ref({id: '', name: '', url: ''})
const fileList = ref([])
const uped = ref(true)

onMounted(() => {
  selType()
  fileList.value = props.files && props.files.length>0 ? props.files : []
  fileRef.value = props.file && props.file.id && props.file.id!=='' ? props.file : {id: '', name: '', url: ''}
  uped.value = !(fileRef.value && fileRef.value.id && fileRef.value.id !== '')
})


// 定义子组件调用父组件的方法
const emits = defineEmits(['setUrl'])

// 上传表单
const fileForm = ref('fileForm')

// selFile 选择文件
const fileShow = ref(false)
const selFile = () => {
  fileShow.value = true
  if(!allList.value || allList.value.length===0) {
    list(0,1)
  } else {
    allList.value.forEach(cur => {
      cur.seled = false
      if(fileRef.value && cur.fileId===fileRef.value.id) {
        cur.seled = true
      } else if(fileList.value) {
        fileList.value.forEach(item => {
          if(cur.fileId === item.id) {
            cur.seled = true
          }
        })
      }
    })
  }
}

// selType 获取分类下拉列表
const typeList = ref([])
const selType = async () => {
  const res = await treeDictsApi({kind: 2, typeCode: 'SYS_FILE'})
  if(res.code === import.meta.env.VITE_SUCCESS_CODE) {
    typeList.value = res.data
  }
}

const schRef = ref({
  keywords: '',
  fileType: '',
  typeName: '',
  typeCode: '',
  kind: props.kind===1 || props.kind===2 ? 1 : 0,
  kindName: '',
  kindCode: '',
  offset: 0,
  limit: 18
})
const total = ref(0)
const curPage = ref(1)
const allList = ref([])
const hasData = ref(false)
// list 列表展示
const list = async (offset, cur) => {
  schRef.value.offset = offset || 0
  curPage.value = cur || 1
  hasData.value = false
  const res = await pageFilesApi(schRef.value)
  if(res.code === import.meta.env.VITE_SUCCESS_CODE && res.data) {
    hasData.value = true
    total.value = res.data.total
    allList.value = res.data.list
    allList.value.forEach(cur => {
      cur.seled = false
      if(props.file && cur.fileId===props.file.id) {
        cur.seled = true
      } else if(props.files) {
        props.files.forEach(item => {
          if(cur.fileId === item.id) {
            cur.seled = true
          }
        })
      }
    })
  }
}

const setValue = (item, kind) => {
  switch(kind) {
    case 1:
      schRef.value.fileType = item.selId
      schRef.value.typeName = item.selName
      schRef.value.typeCode = item.selCode
      break
    case 2:
      schRef.value.kind = item.selId
      schRef.value.kindName = item.selName
      schRef.value.kindCode = item.selCode
      break
  }
}

// clrSch 重置搜索框
const clrSch = () => {
  schRef.value = {
    keywords: '',
    fileType: '',
    typeName: '',
    typeCode: '',
    kind: props.kind===1 || props.kind===2 ? 1 : 0,
    kindName: '',
    kindCode: '',
    offset: 0,
    limit: 18
  }
  list(0, 1)
}

// setFile 选中文件
const setFile = (curFile) => {
  if(props.kind===1 || props.kind===3) {
    // 单文件
    uped.value = false
    allList.value.forEach(item => {
      item.seled = item.fileId === curFile.fileId;
    })
    fileRef.value = { id: curFile.fileId, name: curFile.fileName, url: curFile.visitUrl }
    emits('setUrl', props.kind, props.types, fileRef.value)
  } else {
    // 多文件
    allList.value.forEach(item => {
      if(item.fileId === curFile.fileId) {
        item.seled = true
      }
    })
    let exists = false
    fileList.value.forEach(curf => {
      if(curFile.fileId === curf.id) {
        exists = true
      }
    })
    if(exists) {
      const index = fileList.value.findIndex(cfile => {
        allList.value.forEach(item => {
          if(curFile.fileId === item.fileId) {
            item.seled = false
          }
        })
        if(cfile.id === curFile.fileId){
          return true
        }
      })
      fileList.value.splice(index, 1)
    } else {
      let cur = { id: curFile.fileId, name: curFile.fileName, url: curFile.visitUrl }
      fileList.value.push(cur)
      emits('setUrl', props.kind, props.types, fileList.value)
    }
  }
}

// remove 删除当前文件
const remove = (fileId) => {
  if(!fileId || fileId==='') {
    Msg({ kind: 'warn', txt: '请求的参数不能为空！' })
    return
  }
  if(props.kind===1 || props.kind===3) {
    uped.value = true
    fileRef.value = {id: '', name: '', url: ''}
    emits("setUrl", props.kind, props.types, fileRef.value)
  } else {
    fileList.value.splice(fileList.value.findIndex(cur => cur.id === fileId), 1)
    emits('setUrl', props.kind, props.types, fileList.value)
  }
}

// view 预览图片
const showed = ref(false)
const imgRef = ref({name: '', url: ''})
const view = (name, url) => {
  showed.value = true
  imgRef.value.name = name
  imgRef.value.url = url
}

// close 关闭预览框
const close = (kind) => {
  if(kind === 1) {
    fileShow.value = false
  } else {
    showed.value = false
    imgRef.value = {name: '', url: ''}
  }
}

// upload 上传文件
const upload = async (event) => {
  if(event) {
    let file = event.target.files[0]
    let allowed = props.kind===1 || props.kind===2 ? 'image/jpeg|image/png|image/bmp|image/gif' : 'image/jpeg|image/png|image/bmp|image/gif|text/plain|text/css|text/csv|application/vnd.ms-works|application/msword|application/pdf|application/vnd.ms-powerpoint|application/vnd.ms-excel|audio/mp4|video/mp4|aplication/zip|application/vnd.openxmlformats-officedocument.spreadsheetml.sheet|application/vnd.openxmlformats-officedocument.wordprocessingml.document|application/vnd.openxmlformats-officedocument.presentationml.presentation'
    if(!file || allowed.indexOf(file.type) === -1) {
      Msg({kind: 'error', txt: '对不起，平台不允许上传该格式的文件，请改换！'})
      return
    } else {
      let formData = new FormData()
      formData.append('upFile', file)
      const res = await upFileApi(formData)
      if(res.code === import.meta.env.VITE_SUCCESS_CODE) {
        await ist(0, 1)
        Msg({kind: 'success', txt: '文件上传成功！'})
      } else {
        Msg({kind: 'error', txt: res.msg})
      }
    }
  }
  fileForm.value.value = ''
}
// download 下载文件
const download = async (fileId) => {
  // axios.post('http://api.dcwm.com/system/file/download', {fileId}, {
  axios.post('http://127.0.0.1:7001/system/file/download', {fileId}, {
    headers: {'token': localStorage.getItem("token")},
    responseType: 'blob'
  }).then(res => {
    let aTag = document.createElement("a")
    aTag.href = window.URL.createObjectURL(new Blob([res.data]))
    aTag.download = decodeURI(res.headers['content-disposition'].split('=')[1].replace(' ', ''))
    aTag.click()
    window.URL.revokeObjectURL(aTag.href)
  }).catch(function (err) {
    Msg({kind: 'error', txt: err})
  })
}
</script>

<template>
  <div class="up-a">
    <div class="up-a" v-if="props.kind===1 || props.kind===2">
      <div class="up-b" v-if="props.kind===1">
        <div class="up-c" v-if="uped" @click="selFile()"><i class="iconfont fs30">&#xea80;</i></div>
        <div v-else>
          <div class="up-d"><img :alt="fileRef.name" v-lazy="fileRef.url.replace('/img/', '/img/thumb/')" class="up-e" /></div>
          <div class="up-f">
            <div class="up-g" @click="view(fileRef.name, fileRef.url)"><i class="iconfont fs20">&#xea8d;</i></div>
            <div class="up-g" @click="remove(fileRef.id)"><i class="iconfont fs20">&#xea45;</i></div>
          </div>
        </div>
      </div>
      <div class="up-b" v-if="props.kind===2">
        <div class="up-c" @click="selFile()"><i class="iconfont fs30">&#xea80;</i></div>
        <div v-for="cur in fileList" :key="cur.id">
          <transition name="fade-mod" appear>
            <div class="up-d"><img :alt="cur.name" v-lazy="cur.url.replace('/img/', '/img/thumb/')" class="up-e" /></div>
          </transition>
          <div class="up-f">
            <div class="up-g" @click="view(cur.name, cur.url)"><i class="iconfont fs20">&#xea8d;</i></div>
            <div class="up-g" @click="remove(cur.id)"><i class="iconfont fs20">&#xea45;</i></div>
          </div>
        </div>
      </div>
    </div>
    <div class="up-a" v-if="props.kind===3 || props.kind===4">
      <div class="up-a" v-if="props.kind===3">
        <div class="up-h" v-if="uped" @click="selFile()"><i class="iconfont">&#xea80;</i> 上传文件</div>
        <div class="up-i" v-else>
          <div class="up-j"><i class="iconfont">&#xea32;</i> {{fileRef.name}}</div>
          <div class="up-k" @click="download(fileRef.id)"><i class="iconfont">&#xeaa2;</i> 下载</div>
          <div class="up-k2" @click="remove(fileRef.id)"><i class="iconfont">&#xea45;</i> 删除</div>
        </div>
      </div>
      <div class="up-a" v-if="props.kind===4">
        <div class="up-h" @click="selFile()"><i class="iconfont">&#xea80;</i> 上传文件</div>
        <div class="up-i" v-for="cur in fileList" :key="cur.id">
          <div class="up-j"><i class="iconfont">&#xea32;</i> {{cur.name}}</div>
          <div class="up-k" @click="download(cur.id)"><i class="iconfont">&#xeaa2;</i> 下载</div>
          <div class="up-k2" @click="remove(cur.id)"><i class="iconfont">&#xea45;</i> 删除</div>
        </div>
      </div>
    </div>
    <transition name="fade-mod" appear>
      <div v-show="fileShow" class="modal-backdrop">
        <c-scrollbar>
          <div v-if="fileShow" class="modal" style="width: 1100px;">
            <div class="modal-header">
              <div class="header-left"><i class="iconfont fs30">&#xea54;</i> 文件选择列表</div>
              <div class="header-right" @click="close(1)"><i class="iconfont fs20">&#xea7f;</i></div>
            </div>
            <div class="modal-body">
              <div class="up-l">
                <div class="btn-pi mr15"><i class="iconfont">&#xea80;</i> 新增文件<input type="file" ref="fileForm" class="up-t" @change="upload($event)" /></div>
                <div class="up-m mr15"><tree-sel :kind="1" :tree-list="typeList" :inboxed="false" :curName="schRef.typeName!=='' ? schRef.typeName+'['+schRef.typeCode+']' : ''" pre-name="分类" @setValue="setValue" /></div>
                <div class="up-m"><input type="text" v-model="schRef.keywords" placeholder="请输入名称的关键字" class="up-n" /></div>
                <div class="btn-pi mr15" @click="list(0, 1)"><i class="iconfont">&#xea49;</i> 筛选</div>
                <div class="btn-d" @click="clrSch()"><i class="iconfont">&#xea4f;</i> 重置</div>
              </div>
              <div class="up-o" v-if="hasData">
                <div class="up-p">
                  <div :class="[curFile.seled ? 'up-u' : 'up-q']" v-for="curFile in allList" :key="curFile.fileId" @click="setFile(curFile)">
                    <div class="up-r"><img :alt="curFile.fileName+curFile.fileExt" v-lazy="curFile.kind===1 ? curFile.visitUrl.replace('/img/', '/img/thumb/') : nopic" class="max-img" /></div>
                    <div class="up-s">{{curFile.fileName}}</div>
                  </div>
                </div>
                <pager v-if="hasData" :limit="schRef.limit" :total="total" :page="curPage" @turn="list" />
              </div>
              <div v-else class="no-data">暂无内容</div>
            </div>
            <div class="modal-footer">
              <div class="btn-pi" @click="close(1)"><i class="iconfont">&#xea7c;</i> 确定</div>
            </div>
          </div>
        </c-scrollbar>
      </div>
    </transition>
    <transition name="fade-mod" appear>
      <div v-show="showed" class="modal-backdrop">
        <c-scrollbar>
          <div v-if="showed" class="modal" style="width: 1100px;">
            <div class="modal-header">
              <div class="header-left"><i class="iconfont">&#xea54;</i> 图片详情</div>
              <div class="header-right" @click="close(2)"><i class="iconfont fs20">&#xea7f;</i></div>
            </div>
            <div class="modal-body">
              <div class="up-v"><img :alt="imgRef.name" v-lazy="imgRef.url" class="up-w" /></div>
            </div>
            <div class="modal-footer">
              <div class="btn-d up-x" @click="close(2)"><i class="iconfont">&#xea4f;</i> 关闭</div>
            </div>
          </div>
        </c-scrollbar>
      </div>
    </transition>
  </div>
</template>

<style scoped>
.up-a {width: 100%;}
.up-b {display: inline-flex; display: -webkit-inline-flex; flex-wrap: wrap;}
.up-c {padding: 30px; margin: 0 15px 15px 0; position: relative; color:#409EFF; background-color: #FFF; border: 1px dashed #4099FF; border-radius: 4px; cursor: pointer;}
.up-c:hover {border: 1px solid #66B1FF;}
.up-d {width: 90px; height: 90px; margin-right: 15px; overflow: hidden; border: 1px solid #4099FF; border-radius: 4px; text-align: center;}
.up-e {height: 100%;}
.up-f {width: 91px; height: 91px; border-radius: 4px; margin-right: 16px; margin-top: -91px; position: relative; opacity: 0; cursor: pointer;}
.up-f:hover {opacity: 1; background-color: rgba(0, 0, 0, .5);}
.up-g {padding-top: 15px; text-align: center; color: #FFF;}

.up-h {width: 85px; height: 20px; padding: 5px 10px; position: relative; color:#FFF; background-color: #409EFF; border-radius: 4px; cursor: pointer;}
.up-h:hover {background-color: #66B1FF;}
.up-i {width: calc(100% - 40px); line-height: 30px; padding: 10px 20px; border-bottom: 1px dashed #E0E0E0; display: flex; display: -webkit-flex;}
.up-j {flex-grow: 1;}
.up-k {width: 100px; text-align: right; cursor: pointer; color: #4099FF;}
.up-k2 {width: 100px; text-align: right; cursor: pointer; color: #d03050;}

.up-l {margin: 0 10px 10px 10px; border: 1px dashed #DDD; display: flex; display: -webkit-flex; padding: 15px 15px 0 15px; flex-wrap: wrap; justify-content: flex-end;}
.up-m {flex-grow: 1; margin-bottom: 15px;}
.up-n {width: 230px; padding: 8px;}
.up-o {background-color: #FFF;}
.up-p {display: flex; display: -webkit-flex; flex-wrap: wrap; padding: 5px;}
.up-q {width: 153px; border: 1px #EBEBEB solid; padding: 0 5px; margin: 5px;}
.up-q:hover {box-shadow: #CCC 0 0 5px;}
.up-r {width: 150px; height: 150px; overflow: hidden; padding: 2px; text-align: center; cursor: pointer; display: flex; align-items: center; justify-content: center;}
.up-s {height: 30px; text-align: center;}
.up-t {position: absolute; opacity: 0; width: 92px; height: 32px; margin-left: -84px; cursor: pointer;}
.up-u {width: 153px; border: 1px #4099FF solid; padding: 0 5px; margin: 5px;}

.up-v {text-align: center;}
.up-w {max-width: 100%;}
.up-x {margin: 10px 15px; cursor: pointer;}
</style>
